//
//  XFAudioHelper.m
//  test
//
//  Created by mac on 2017/9/6.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "XFAudioHelper.h"

#import "iflyMSC/IFlySpeechUtility.h"
#import "iflyMSC/IFlySpeechConstant.h"
#import "iflyMSC/IFlySpeechRecognizer.h"
#import "iflyMSC/IFlyDataUploader.h"
#import "iflyMSC/IFlyResourceUtil.h"
#import "iflyMSC/IFlySpeechError.h"
#import "ISRDataHelper.h"

#define kOFFSET_FOR_KEYBOARD 110.0
#define GRAMMAR_TYPE_BNF    @"bnf"




@interface XFAudioHelper()
{
    NSString *grammarType;
}


@end


@implementation XFAudioHelper

@synthesize delegate;

- (instancetype) init
{
    self = [super init];
    if (!self) {
        return nil;
    }
    return self;
}





-(void) build{
    grammarType = GRAMMAR_TYPE_BNF;
    self.curResult = [[NSMutableString alloc]init];
    [_iFlySpeechRecognizer stopListening];
    [self buildGrammer];
}

//开始录音
-(void) start_record{
    [_iFlySpeechRecognizer startListening];
}
//停止录音
-(void) stop_record{
    [IFlySpeechRecognizer.sharedInstance stopListening];
    [_resultView resignFirstResponder];
}
//释放内存
-(void) dealloc_audio{
    //[_iFlySpeechRecognizer dealloc];
}



- (void) onResults:(NSArray *) results isLast:(BOOL) isLast{
    NSMutableString * resultString = [[NSMutableString alloc]init];
    NSDictionary *dic = results[0];
    NSArray *keys = [dic allKeys];
    for (NSString *key in keys) {
        NSString *res = [ISRDataHelper stringFromAsr:key];
        [resultString appendString:res];
    }
    if (isLast) {
        NSLog(@"result is:%@",self.curResult);
    }
    [self.curResult appendString:resultString];
    
}
//会话结束回调
- (void) onError:(IFlySpeechError*) error{
    NSLog(@"会话结束回调");
    NSString *result;
    if (self.isCanceled) {
        result = @"识别取消";
        [delegate onResult:false results:result]; //调用头文件定义的协议
    }else if (error.errorCode ==0 ) {
        if (self.curResult.length==0 || [self.curResult hasPrefix:@"nomatch"]) {
             result = @"无匹配结果";
            [delegate onResult:false results:result]; //调用头文件定义的协议
        }else{
            result = self.curResult;
            [delegate onResult:true results:result]; //调用头文件定义的协议
        }
    }else{
        result = @"发生错误";
         [delegate onResult:false results:result];//调用回调函数
    }
    [self.curResult setString:@""];

}
//录音音量回调
- (void) onVolumeChanged: (int)volume{
    NSLog(@"录音音量回调");
}
//录音开始回调
- (void) onBeginOfSpeech{
    NSLog(@"录音开始回调");
}
//录音结束回调
- (void) onEndOfSpeech{
    NSLog(@"录音结束回调");
}
//会话取消回调
- (void) onCancel{
    NSLog(@"会话取消回调");
}




-(void)buildGrammer{
    NSString *appPath = [[NSBundle mainBundle] resourcePath];
    //获取识别对象单例
    _iFlySpeechRecognizer = [IFlySpeechRecognizer sharedInstance];
    //设置协议委托对象
    _iFlySpeechRecognizer.delegate = self;
    //设置引擎类型，cloud 或者 local
    [_iFlySpeechRecognizer setParameter:@ "local" forKey:[IFlySpeechConstant ENGINE_TYPE]];
    //语法类型，本地是 bnf，在线识别是 abnf
    [_iFlySpeechRecognizer setParameter:@ "bnf" forKey:[IFlyResourceUtil GRAMMARTYPE]];
    
    NSString *documentsPath = nil;
    NSArray *appArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    if ([appArray count] > 0) {
        documentsPath = [appArray objectAtIndex:0];
    }
    NSString *grammBuildPath = [documentsPath stringByAppendingString:@"/grm"];
    [_iFlySpeechRecognizer setParameter:grammBuildPath forKey:[IFlyResourceUtil GRM_BUILD_PATH]];
    //设置引擎资源文件路径，如 demo 中的 aitalkResource 中的 common.mp3
    NSString *aitalkResourcePath = [[NSString alloc] initWithFormat:@"fo|%@/aitalkResource/common.mp3",appPath];
    [_iFlySpeechRecognizer setParameter:aitalkResourcePath forKey:[IFlyResourceUtil ASR_RES_PATH]];
    //启动 asr 识别引擎
    [[IFlySpeechUtility getUtility] setParameter:@"asr" forKey:[IFlyResourceUtil ENGINE_START]];
    //编译语法文件（注意 grammarType 参数的区别）
    //读取本地 bnf 语法文件内容
    NSString *bnfFilePath = [[NSString alloc] initWithFormat:@"%@/bnf/call.bnf",appPath];
    NSString* grammarContent = [self readFile:bnfFilePath];
    //调用语法编译接口
    [_iFlySpeechRecognizer buildGrammarCompletionHandler:^(NSString * grammerID, IFlySpeechError *error){
        dispatch_async(dispatch_get_main_queue(), ^{
            if (![error errorCode]) {
                //label.text = @"成功";
            }else{
                NSLog(@"失败:%@",[error errorDesc]);
            }
            //设置 grammerID
            [_iFlySpeechRecognizer setParameter:grammerID forKey:[IFlySpeechConstant LOCAL_GRAMMAR]];
        });
    }grammarType: grammarType grammarContent:grammarContent];
    
}

/*
 *****文件读取*****
 */
-(NSString *)readFile:(NSString *)filePath
{
    NSData *reader = [NSData dataWithContentsOfFile:filePath];
    return [[NSString alloc] initWithData:reader
                                 encoding:NSUTF8StringEncoding];
}

@end
